import login from "./login";

export const baseUrl = "https://proxy.qingful.com/lover";
export const wssUrl = "wss://proxy.qingful.com/lover";
export const imgUrl = "https://proxy.qingful.com/lover/uploads/";
export const loginUrl = "https://api.qingful.com/api/public/wxa_login";
export const wxpayUrl = "https://api.qingful.com/pay/wxpay/index";

export default function fetch(url, params) {

  if (url.substr(0, 7) !== 'http://' && url.substr(0, 8) !== 'https://') {
    url = baseUrl + url;
  }

  if (params) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: url,
        method: "POST",
        data: params,
        header: {
          'Authorization': wx.getStorageSync("token"),
          'content-type': 'application/json'
        },
        success: function (res) {
          // if (res.statusCode == 401) {
          //   return resolve(tryLogin(url, params));
          // } else {
            resolve(res);
          // }
        },
        fail: function (res) {
          reject(res);
        },
        complete: function (res) {

        }
      });
    });
  }

  return new Promise((resolve, reject) => {
    wx.request({
      url: url,
      method: "GET",
      header: {
        'Authorization': wx.getStorageSync("token"),
        'content-type': 'application/json'
      },
      success: function (res) {
        if (res.statusCode == 401) {
          return resolve(tryLogin(url, params));
        } else {
          resolve(res);
        }
      },
      fail: function (res) {
        reject(res);
      },
      complete: function (res) {

      }
    });
  });
}

export function tryLogin(url, params) {
  return login().then(loginParams => {
    return fetch(loginUrl, loginParams).then(res => {
      if (res && res.data.code) {
        wx.setStorageSync("token", res.data.data.token);
        return fetch(url, params);
      } else {
        wx.showModal({
          content: res.data.data,
          showCancel: false
        });
        return res;
      }
    });
  });
}

export function upload(url, name, files, form = {}) {
  return new Promise((resolve, reject) => {
    wx.uploadFile({
      url: baseUrl + url,
      filePath: files,
      name: name,
      formData: form,
      header: {
        'Authorization': wx.getStorageSync("token"),
      },
      success: function (res) {
        resolve(res);
      },
      fail: function (res) {
        reject(res);
      },
      complete: function (res) {

      }
    })
  });
}